from django.contrib.auth.models import User
from django.shortcuts import redirect, render, get_object_or_404
from django.http import HttpResponse, Http404
from .forms import NewTopicForm
from .models import Board, Topic, Post

# Create your views here.

def home(request):
    """网站主页
    """
    boards = Board.objects.all()
    return render(request, 'home.html', {'boards': boards})


def board_topics(request, pk):
    """板块下的话题列表页面
    """
    board = get_object_or_404(Board, pk=pk)
    return render(request, 'topics.html', {'board': board})

"""
def new_topic(request, pk):
    ""新话题提交页面
    ""
    board = get_object_or_404(Board, pk=pk)

    if request.method == 'POST':
        subject = request.POST['subject']
        message = request.POST['message']

        user = User.objects.first()  # 临时使用一个临时账户

        topic = Topic.objects.create(
            subject = subject,
            board = board,
            starter = user
        )

        post = Post.objects.create(
            message = message,
            topic = topic,
            created_by = user
        )

        return redirect('board_topics', pk=board.pk)

    return render(request, 'new_topic.html', {'board': board})
"""

def new_topic(request, pk):
    board = get_object_or_404(Board, pk=pk)
    user = User.objects.first()  # TODO: get the currently logged in user
    if request.method == 'POST':
        form = NewTopicForm(request.POST)  # 实例化一个将 POST 数据传递给 form 的 form 实例
        if form.is_valid():  # 检查表单数据是否有效
            topic = form.save(commit=False)  # 数据有效，存入数据库中，返回一个存入数据库的 Model 实例
            topic.board = board
            topic.starter = user
            topic.save()
            post = Post.objects.create(
                message=form.cleaned_data.get('message'),
                topic=topic,
                created_by=user
            )
            return redirect('board_topics', pk=board.pk)
    else:
        form = NewTopicForm()
    return render(request, 'new_topic.html', {'board': board, 'form': form})
